package com.shuqi.activity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.MyBookBagAdapter;
import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.bookbag.BookBagDao;
import com.shuqi.bookbag.BookBagInfo;
import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.MyTask;
import com.shuqi.common.utils.BookBagUtil;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookBagCatalogDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.BookContentLocalAppBagParser.BookBagCatalogHandler;
import com.shuqi.model.parse.parser.XMLHelper;

/**
 * 我的书包
 * 
 * @author yanghuawei
 * 
 */
public class MyBookBagActivity extends ActivityBase implements OnClickListener {

    private final int Msg_loadData_start = 1;
    private final int Msg_loadData_finish = 2;
    private final int Msg_refreshAdapter = 3;
    private final int Msg_showSDCardError = 4;
    private final int Msg_showNoBag = 5;
    private List<MyBook> books;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Msg_loadData_start:
                    loadData();
                    break;
                case Msg_loadData_finish:
                    refreshUI();
                    break;
                case Msg_showSDCardError:
                    showErrorPage(true);
                    break;
                case Msg_showNoBag:
                    showErrorPage(false);
                    break;
                case Msg_refreshAdapter:
                    if(adapter!=null){
                        adapter.notifyDataSetChanged();
                    }
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_mybookbag);
        initPage();
        if (Util.isCanUseSdCard()) {
            handler.sendEmptyMessage(Msg_loadData_start);
        } else {
            handler.sendEmptyMessage(Msg_showSDCardError);
        }
    }

    /*** 初始化页面view */
    private void initPage() {
        findViewById(R.id.mybookbag_listview).setVisibility(View.GONE);
        findViewById(R.id.mybookbag_none).setVisibility(View.GONE);
        ((CommonTitle) findViewById(R.id.title)).setLeftClickListener(this);
    }

    /***
     * 显示错误页面
     * 
     * @param isSDcardOk 是否为sd不可用
     */
    private void showErrorPage(boolean isSDcardError) {
        findViewById(R.id.mybookbag_listview).setVisibility(View.GONE);
        findViewById(R.id.mybookbag_none).setVisibility(View.VISIBLE);
        TextView tv = (TextView) findViewById(R.id.mybookbag_none_tv);
        tv.setCompoundDrawablesWithIntrinsicBounds(0, isSDcardError ? R.drawable.icon_err_nosdcard
                : R.drawable.limit_nodata, 0, 0);
    }
    
    /***
     * 解析书包数据
     * @param bookBagInfo
     * @param mCatalogHandler
     * @return
     */
    private List<BookContentInfo> getList(BookBagInfo bookBagInfo,
            BookBagCatalogHandler mCatalogHandler) {
        String filePath = Config.BOOKBAG_PATH + "/" + bookBagInfo.getFileName();
        ByteArrayOutputStream as = BookBagUtil.decode2Zip(filePath, ConfigVersion.SN);
        ByteArrayInputStream is = BookBagUtil.unzip(as, "chapterinfo.xml");
        XMLHelper.doInputSteamParse(mCatalogHandler, is);
        return mCatalogHandler.getParsedData();
    }

    private void loadData() {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                books = null;
                long start = System.currentTimeMillis();
                List<BookBagInfo> list = BookBagDao.getInstance().getBookBagList();
                if(list!=null && list.size()>0){
                    long time1 = System.currentTimeMillis();
                    Map<String, MyBook> bags = new HashMap<String, MyBook>();
                    BookBagCatalogHandler mCatalogHandler = new BookBagCatalogHandler();
                    int num = 0;
                    for (BookBagInfo bookBagInfo : list) {
                        MyBook book = bags.get(bookBagInfo.getBookId());
                        if (book == null) {
                            book = new MyBook();
                            
                            book.bookId = bookBagInfo.getBookId();
                            book.bookName = bookBagInfo.getBookName();
                            book.author = bookBagInfo.getAuthor();
                            book.bagUrl = bookBagInfo.getImgUrl();
                            
                            book.fileName = bookBagInfo.getFileName();
                            book.packageId = Integer.parseInt(bookBagInfo.getPackageId());
                            List<BookContentInfo> bagChapterList =
                                    getList(bookBagInfo, mCatalogHandler);
                            if (bagChapterList != null && bagChapterList.size() > 0) {
                                book.chapterId = bagChapterList.get(0).getCurChapterCid();
                                book.chapterName = bagChapterList.get(0).getCurChapterName();
                                book.numBag += 1;
                                book.numChapter += bagChapterList.size();
                            }
                            bags.put(book.bookId, book);
                        } else {
                            List<BookContentInfo> bagChapterList =
                                    getList(bookBagInfo, mCatalogHandler);
                            if (bagChapterList != null && bagChapterList.size() > 0) {
                                book.numBag += 1;
                                book.numChapter += bagChapterList.size();
                                book.fileName = bookBagInfo.getFileName();
                                book.chapterId = bagChapterList.get(0).getCurChapterCid();
                                book.chapterName = bagChapterList.get(0).getCurChapterName();
                                book.packageId = Integer.parseInt(bookBagInfo.getPackageId());
                            }
                        }
                        Log4an.i("MyBookBagActivity", num++ + "_" + book.toString());
                    }
                    long time2 = System.currentTimeMillis();
                    if (bags != null && bags.size() > 0) {
                        Set<Entry<String, MyBook>> set = bags.entrySet();
                        books = new ArrayList<MyBookBagActivity.MyBook>();
                        for (Entry<String, MyBook> entry : set) {
                            books.add(entry.getValue());
                        }
                    }
                    Log4an.i("MyBookBagActivity", " 读库=" + (time1 - start) + " 解析读数据=" + "time1="
                            + (time2 - start));
                }
                handler.sendEmptyMessage(Msg_loadData_finish);
            }
        };
        MyTask.runInBackground(run, true);
    }
    private MyBookBagAdapter adapter;
    private ListView listView;
    
    private void refreshUI() {
        if (books != null && books.size() > 0) {
            adapter = new MyBookBagAdapter(this, books);
            listView = (ListView) findViewById(R.id.mybookbag_listview);
            listView.setVisibility(View.VISIBLE);
            findViewById(R.id.mybookbag_none).setVisibility(View.GONE);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (books != null && books.size() > 0 && position < books.size()) {
                        MyBook book = books.get(position);
                        Log4an.i("", book.toString());
                        startReadBookBag(book);
                    }
                }
            });
            OnItemLongClickListener longListener = new OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int position,
                        long id) {
                    Log4an.e("", "onItemLongClick position="+position+"_"+books.get(position).getBookName());
                    View v = View.inflate(MyBookBagActivity.this, R.layout.view_dialog_common, null);
                    ((TextView)v.findViewById(R.id.dialog_common_tips)).setText("你确定要删除此书的所有书包吗？");
                    
                    final BottomDialog mDialogDeleteBag = new BottomDialog(MyBookBagActivity.this, v);
                    OnClickListener listener = new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getId() == R.id.dialog_common_cancel) {
                                mDialogDeleteBag.dismiss();
                            } else if (v.getId() == R.id.dialog_common_confirm) {
                                mDialogDeleteBag.dismiss();
                                if (books != null && books.size() > 0 && position < books.size()) {
                                    MyBook book = books.get(position);
                                    deleteBookBagsByBookId(book.bookId);
                                }else if(books != null){
                                    Log4an.e("", "onItemLongClick size="+books.size()+"_position="+position);
                                }else{
                                    Log4an.e("", "books is null");
                                }
                            }
                        }
                    };
                    v.findViewById(R.id.dialog_common_cancel).setOnClickListener(listener);
                    v.findViewById(R.id.dialog_common_confirm).setOnClickListener(listener);
                    mDialogDeleteBag.show();
                    return true;
                }
            };
            listView.setOnItemLongClickListener(longListener);
        } else {
            handler.sendEmptyMessage(Msg_showNoBag);
        }
    }
    /***
     * 删除书包以及相关数据
     * @param bookId
     * @return
     */
    private boolean deleteBookBagsByBookId(final String bookId){
        Log4an.e("", "delete bookId is "+bookId);
        if(TextUtils.isEmpty(bookId)){
            return false;
        }
        MyTask.runInBackground(new Runnable() {
            @Override
            public void run() {

                BookMarkInfo bookMarkInfo = new BookMarkInfo();
                bookMarkInfo.setBookType(BookMarkInfo.TYPE_OLD_BAG_BOOKMARK);
                bookMarkInfo.setBookId(bookId);
                int delteMarkNum = BookMarkInfoDao.getInstance().delBookMark(bookMarkInfo);
                Log4an.e("", "删除书签："+delteMarkNum);
                List<BookContentInfo> catalog = BookBagCatalogDao.getInstance().getBookBagCatalogList(bookId);
                int numCatalog = catalog==null?0:catalog.size();
                int delteCatalogNum = BookBagCatalogDao.getInstance().deleteCatalogByBagBookId(bookId);
                Log4an.e("", "目录条数："+numCatalog+",删除目录："+delteCatalogNum);
                int delteBookBagNum = BookBagDao.getInstance().deleteBookBagsByBookId(bookId);
                Log4an.e("", "删除书包表："+delteBookBagNum);
                //删除书包文件
                BookBagUtil.deletBookBagData(bookId);
                for (int i = 0; books!=null && i < books.size();i++) {
                    if(bookId.equals(books.get(i).getBookId())){
                        books.remove(i);
                        break;
                    }
                }
                handler.sendEmptyMessage(Msg_refreshAdapter);
                if(books.size()<1){
                    handler.sendEmptyMessage(Msg_showNoBag);
                }
            }
        }, true);
        return false;
    }

    /***
     * 从书包开始阅读
     */
    private void startReadBookBag(MyBook book) {
        if (book != null && !TextUtils.isEmpty(book.bookId)) {
            UserInfo user = MyAccountManager.getInstance(this);
            BookMarkInfo mark = BookMarkInfoDao.getInstance().getBookBagMark(book.bookId);
            if (mark == null) {
                mark = new BookMarkInfo();
                mark.setBookId(book.bookId);
                mark.setChapterId(book.chapterId);
                mark.setChapterName(book.chapterName);
                mark.setBookName(book.bookName);
                mark.setBookType(BookMarkInfo.TYPE_OLD_BAG_BOOKMARK);
                mark.setFilePath(book.fileName);
                mark.setUserId(user.getUserId());
            }
            Log4an.i("MyBookBagActivity", "startReadBookBag() " + mark.toString());
            if(Util.isCanUseSdCard()){
                EnterBookContent.jumpToBookContentByBookMark(this, mark,-1);
            }else{
                ToastUtil.showMessage("SD卡不可用");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
        }
    }

    /**
     * 打开我的书包页面
     */
    public static void show(Activity activity) {
        Intent intent = new Intent(activity, MyBookBagActivity.class);
        ActivityManager.getInstance().startNextActivity(intent, activity);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void activityLogicForward() {}

    @Override
    public void activityInitData() {}

    public class MyBook {
        private String bookId;
        private String bookName;
        private String author;
        private String fileName;
        private String chapterId;
        private String chapterName;
        private String bagUrl;
        private int numBag;
        private int numChapter;
        private int packageId;

        public MyBook() {}

        public String getBookId() {
            return bookId;
        }

        public void setBookId(String bookId) {
            this.bookId = bookId;
        }

        public String getBookName() {
            return bookName;
        }

        public void setBookName(String bookName) {
            this.bookName = bookName;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getChapterId() {
            return chapterId;
        }

        public void setChapterId(String chapterId) {
            this.chapterId = chapterId;
        }

        public String getChapterName() {
            return chapterName;
        }

        public void setChapterName(String chapterName) {
            this.chapterName = chapterName;
        }

        public String getBagUrl() {
            return bagUrl;
        }

        public void setBagUrl(String bagUrl) {
            this.bagUrl = bagUrl;
        }

        public int getNumBag() {
            return numBag;
        }

        public void setNumBag(int numBag) {
            this.numBag = numBag;
        }

        public int getNumChapter() {
            return numChapter;
        }

        public void setNumChapter(int numChapter) {
            this.numChapter = numChapter;
        }

        public int getPackageId() {
            return packageId;
        }

        public void setPackageId(int packageId) {
            this.packageId = packageId;
        }

        @Override
        public String toString() {
            return "MyBook [bookId=" + bookId + ", bookName=" + bookName + ", author=" + author
                    + ", fileName=" + fileName + ", chapterId=" + chapterId + ", chapterName="
                    + chapterName + ", bagUrl=" + bagUrl + ", numBag=" + numBag + ", numChapter="
                    + numChapter + ", packageId=" + packageId + "]";
        }
    }
}
